import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';

import '../drawer_menu.dart';
import 'home_vm.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with WidgetsBindingObserver {
  final HomeViewModel _viewModel = HomeViewModel();

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  Widget build(BuildContext context) {
    final l10n = AppLocalizations.of(context)!;
    final cs = Theme.of(context).colorScheme;
    final tt = Theme.of(context).textTheme;

    double spentPercentage =
        (_viewModel.totalExpenses / _viewModel.budget).clamp(0.0, 1.0);

    // 获取屏幕信息
    final mediaQuery = MediaQuery.of(context);
    final isLandscape = mediaQuery.orientation == Orientation.landscape;

    return Scaffold(
      appBar: AppBar(
        title: Text(l10n.homeTitle, style: tt.titleLarge),
        backgroundColor: cs.surface,
        elevation: 0.5,
        actions: [
          IconButton(
            icon: const Icon(Icons.notifications_outlined),
            onPressed: () {},
          ),
          IconButton(
            icon: const Icon(Icons.settings_outlined),
            onPressed: () {},
          ),
        ],
      ),
      drawer: const DrawerMenu(),
      backgroundColor: Theme.of(context).colorScheme.surface,
      body: SafeArea(
        child: SingleChildScrollView(
          padding: EdgeInsets.all(16.w),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              _buildBalanceCard(isLandscape, spentPercentage),
              SizedBox(height: 16.h),
              _buildSmartSuggestionCard(context),
              SizedBox(height: 16.h),
              _buildQuickActions(context),
              SizedBox(height: 16.h),
              _buildOverviewChart(context),
              SizedBox(height: 16.h),
              _buildRecentList(context),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildBalanceCard(bool isLandscape, double spentPercentage) {
    final theme = Theme.of(context);
    final cs = theme.colorScheme;
    final tt = theme.textTheme;

    final padding = EdgeInsets.all(isLandscape ? 12.w : 12.h);

    return Card(
      elevation: 4,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20.r)),
      clipBehavior: Clip.antiAlias,
      child: Container(
        padding: padding,
        decoration: BoxDecoration(
          gradient: LinearGradient(
            colors: [
              cs.primary.withOpacity(0.85),
              cs.primaryContainer.withOpacity(0.95),
            ],
            begin: Alignment.topLeft,
            end: Alignment.bottomRight,
          ),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _buildHeader(tt),
            SizedBox(height: 8.h),
            _buildTotalBalance(tt),
            SizedBox(height: 20.h),
            _buildBudgetInfo(tt, spentPercentage),
            SizedBox(height: 8.h),
            _buildProgressBar(spentPercentage),
            SizedBox(height: 12.h),
            _buildBudgetExpensesRow(),
          ],
        ),
      ),
    );
  }

  Widget _buildHeader(TextTheme tt) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(
          AppLocalizations.of(context)!.homeTotalBalance,
          style: tt.bodyMedium?.copyWith(
            color: Colors.white70,
            fontSize: 16.sp,
          ),
        ),
        IconButton(
          onPressed: () {},
          icon: const Icon(Icons.edit, color: Colors.white),
          tooltip: AppLocalizations.of(context)!.homeEditBudget,
        ),
      ],
    );
  }

  Widget _buildTotalBalance(TextTheme tt) {
    return Text(
      "\$${_viewModel.totalBalance.toStringAsFixed(2)}",
      style: tt.titleLarge?.copyWith(
        fontSize: 32.sp,
        color: Colors.white,
        fontWeight: FontWeight.bold,
      ),
    );
  }

  Widget _buildBudgetInfo(TextTheme tt, double spentPercentage) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(
          "${AppLocalizations.of(context)!.homeBudget} \$${_viewModel.budget.toStringAsFixed(2)}",
          style: tt.bodySmall?.copyWith(color: Colors.white70),
        ),
        Text(
          "${(spentPercentage * 100).toStringAsFixed(1)}% ${AppLocalizations.of(context)!.homeSend}",
          style: tt.bodySmall?.copyWith(color: Colors.white70),
        ),
      ],
    );
  }

  Widget _buildProgressBar(double spentPercentage) {
    return ClipRRect(
      borderRadius: BorderRadius.circular(10.r),
      child: LinearProgressIndicator(
        value: spentPercentage,
        backgroundColor: Colors.white.withOpacity(0.2),
        valueColor: AlwaysStoppedAnimation<Color>(
          spentPercentage > 0.9
              ? Colors.redAccent
              : spentPercentage > 0.7
                  ? Colors.orange
                  : Colors.greenAccent,
        ),
        minHeight: 8.h,
      ),
    );
  }

  Widget _buildBudgetExpensesRow() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        _buildBudgetExpenseItem(
          icon: Icons.arrow_upward,
          iconColor: Colors.greenAccent,
          label: AppLocalizations.of(context)!.homeBudget,
          value: _viewModel.budget,
        ),
        _buildBudgetExpenseItem(
          icon: Icons.arrow_downward,
          iconColor: Colors.redAccent,
          label: AppLocalizations.of(context)!.homeExpenses,
          value: _viewModel.totalExpenses,
        ),
      ],
    );
  }

  Widget _buildBudgetExpenseItem({
    required IconData icon,
    required Color iconColor,
    required String label,
    required double value,
  }) {
    return Row(
      children: [
        Icon(icon, color: iconColor, size: 18.sp),
        SizedBox(width: 4.w),
        Text(label, style: TextStyle(fontSize: 12.sp, color: Colors.white)),
        SizedBox(width: 4.w),
        Text(
          "\$${value.toStringAsFixed(2)}",
          style: TextStyle(
            fontSize: 12.sp,
            color: Colors.white,
            fontWeight: FontWeight.bold,
          ),
        ),
      ],
    );
  }

  Widget _buildQuickActions(BuildContext context) {
    final cs = Theme.of(context).colorScheme;

    final actions = [
      _QuickActionItem(
        icon: Icons.add,
        label: AppLocalizations.of(context)!.homeAdd,
        color: cs.primary,
        onTap: () {},
      ),
      _QuickActionItem(
        icon: Icons.send,
        label: AppLocalizations.of(context)!.homeSend,
        color: cs.tertiary,
        onTap: () {},
      ),
      _QuickActionItem(
        icon: Icons.bar_chart,
        label: AppLocalizations.of(context)!.homeStats,
        color: cs.secondary,
        onTap: () {},
      ),
      _QuickActionItem(
        icon: Icons.settings_suggest,
        label: AppLocalizations.of(context)!.settingsTitle,
        color: cs.scrim,
        onTap: () {},
      ),
    ];

    return Card(
      elevation: 2,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12.r)),
      child: Padding(
        padding: EdgeInsets.symmetric(vertical: 16.h, horizontal: 12.w),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: actions
              .map((item) => Expanded(
                    child: Padding(
                      padding: EdgeInsets.symmetric(horizontal: 4.w),
                      child: item,
                    ),
                  ))
              .toList(),
        ),
      ),
    );
  }

  Widget _buildOverviewChart(BuildContext context) {
    return Card(
      elevation: 2,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12.r)),
      child: SizedBox(
        height: 180.h,
        child: Center(
          child: Text('Chart Overview Placeholder',
              style: Theme.of(context).textTheme.bodyMedium),
        ),
      ),
    );
  }

  Widget _buildSmartSuggestionCard(BuildContext context) {
    final tt = Theme.of(context).textTheme;
    final cs = Theme.of(context).colorScheme;

    final suggestions = [
      '外卖支出较高，建议设置每周上限',
      '你已连续 5 天未记录支出，是否开启提醒？',
      '娱乐类支出占比偏高，建议设定预算目标',
    ];

    return Card(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12.r)),
      elevation: 2,
      child: Padding(
        padding: EdgeInsets.all(16.w),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(AppLocalizations.of(context)!.homeSmartSuggestions,
                style: tt.titleMedium),
            SizedBox(height: 12.h),
            ...suggestions.map((s) => Padding(
                  padding: EdgeInsets.symmetric(vertical: 6.h),
                  child: Row(
                    children: [
                      Icon(Icons.lightbulb, color: cs.primary, size: 20.sp),
                      SizedBox(width: 8.w),
                      Expanded(child: Text(s, style: tt.bodyMedium)),
                    ],
                  ),
                )),
          ],
        ),
      ),
    );
  }

  Widget _buildRecentList(BuildContext context) {
    final tt = Theme.of(context).textTheme;
    final cs = Theme.of(context).colorScheme;
    return Card(
      elevation: 2,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12.r)),
      child: Padding(
        padding: EdgeInsets.all(16.w),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(AppLocalizations.of(context)!.homeRecentTransactions,
                style: tt.titleMedium?.copyWith(fontWeight: FontWeight.bold)),
            SizedBox(height: 8.h),
            ...List.generate(7, (i) {
              return ListTile(
                dense: true,
                contentPadding: EdgeInsets.zero,
                leading: CircleAvatar(
                  backgroundColor: cs.primary.withOpacity(0.1),
                  child: Icon(Icons.payment, color: cs.primary),
                ),
                title: Text(
                    '${AppLocalizations.of(context)!.homeTransaction} ${i + 1}'),
                subtitle: Text('Aug ${20 + i}, 2025'),
                trailing: Text(
                  '-\$${(i + 1) * 15}.00',
                  style: tt.bodyMedium?.copyWith(
                    color: cs.error,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              );
            }),
          ],
        ),
      ),
    );
  }
}

class _QuickActionItem extends StatelessWidget {
  final IconData icon;
  final String label;
  final Color color;
  final VoidCallback onTap;

  const _QuickActionItem({
    required this.icon,
    required this.label,
    required this.color,
    required this.onTap,
  });

  @override
  Widget build(BuildContext context) {
    final tt = Theme.of(context).textTheme;

    return Column(
      children: [
        Material(
          color: color,
          borderRadius: BorderRadius.circular(8.r),
          child: InkWell(
            onTap: onTap,
            borderRadius: BorderRadius.circular(8.r),
            child: Container(
              width: 48.w,
              height: 48.w,
              alignment: Alignment.center,
              child: Icon(icon, color: Colors.white, size: 24.sp),
            ),
          ),
        ),
        SizedBox(height: 6.h),
        Text(
          label,
          style: tt.bodySmall?.copyWith(
            fontWeight: FontWeight.w500,
            fontSize: 12.sp,
          ),
        ),
      ],
    );
  }
}
